package com.metaverse.backend.service;


import cn.hutool.core.date.DateUtil;
import com.metaverse.backend.config.MinioProperties;
import com.metaverse.backend.utils.ApplicationContextUtil;
import io.minio.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 存储服务
 */
@AllArgsConstructor
@Data
@Slf4j
@Service
public class StorageService {

    /**
     * 上传类型
     */
    public  enum UploadType{
        //默认存储位置
        DEFAULT_UPLOAD("default-upload")
        ;

        private String name;

        UploadType(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

    }

    private MinioProperties minioProperties;

    private MinioClient minioClient;


    /**
     * 上传对象
     * @param uploadName
     * @param inputStream
     * @return
     * @throws IOException
     */
    public String upload(UploadType uploadType, String uploadName, InputStream inputStream) throws Exception {

        HttpServletRequest request = ApplicationContextUtil.currentRequest();
        String contentType = null;

        //检查是否存在bucket
//        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucket()).build());
//        if(!exists){
//            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucket()).build());
//        }

        String uniqueName = System.currentTimeMillis() + "-" + uploadName;
        String objectName =  uploadType.getName() + "/" + DateUtil.formatDate(new Date()) + "/" + uniqueName;
        PutObjectArgs.Builder putObjectArgsBuilder = PutObjectArgs.builder();

        if(StringUtils.isNotEmpty(contentType)){
            putObjectArgsBuilder.contentType(contentType);
        }

        putObjectArgsBuilder.stream(inputStream, inputStream.available(), 1024 * 1024 * 5);
        putObjectArgsBuilder.bucket(minioProperties.getBucket());
        putObjectArgsBuilder.object(objectName);

        try {
            ObjectWriteResponse writeResponse = minioClient.putObject(putObjectArgsBuilder.build());
            String fullPath = minioProperties.getEndpoint() + "/" + writeResponse.bucket() + "/" + writeResponse.object();
            return fullPath;
        }finally {
            if(inputStream != null){
                inputStream.close();
            }
        }

    }
}
